<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams">
            <el-form-item label="科室名称" prop="deptName">
              <el-input v-model="queryParams.deptName" clearable placeholder="请输入科室名称"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="queryParams.status" @change="handleQuery">
                <el-radio value="">全部</el-radio>
                <el-radio v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <!--                    <el-col :span="1.5">-->
            <!--                        <el-button-->
            <!--                            v-hasPerm="['system:dict:export']"-->
            <!--                            icon="el-icon-download"-->
            <!--                            plain-->
            <!--                           -->
            <!--                            type="warning"-->
            <!--                            @click="handleExport"-->
            <!--                        >导出-->
            <!--                        </el-button>-->
            <!--                    </el-col>-->
            <div class="mr20" style="float: right">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPerm="['system:dept:add']" plain type="primary" @click="handleAdd">
              <template
                #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button plain type="info" @click="toggleExpandAll">
              <template
                #icon>
                <i-ep-sort/>
              </template>
              展开/折叠
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button plain type="danger" @click="refreshCacheDeptFun">
              <template
                #icon>
                <i-ep-refresh/>
              </template>
              刷新缓存
            </el-button>
          </el-col>
        </el-row>

        <el-table v-if="refreshTable" v-adaptive :border="true" :data="deptList"
                  :default-expand-all="isExpandAll"
                  :header-cell-style="$headerCellStyle"
                  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" highlight-current-row
                  row-key="deptId">
          <el-table-column label="科室名称" min-width="180" prop="deptName"></el-table-column>
          <el-table-column label="科室代码" min-width="120" prop="deptCode"></el-table-column>
          <el-table-column label="临床标识" min-width="80" prop="clinicalSign">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['clinical_sign']" :value="scope.row.clinicalSign"/>
            </template>
          </el-table-column>
          <el-table-column label="科室属性" min-width="80" prop="deptAttribute">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['dept_attribute']" :value="scope.row.deptAttribute"/>
            </template>
          </el-table-column>
          <el-table-column label="门诊住院" min-width="80" prop="clinicOrVisit">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['clinic_or_visit']" :value="scope.row.clinicOrVisit"/>
            </template>
          </el-table-column>
          <el-table-column label="内外科标识" min-width="90" prop="internalOrSurgery">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['internal_or_surgery']"
                             :value="scope.row.internalOrSurgery"/>
            </template>
          </el-table-column>
          <el-table-column label="所在院区" min-width="80" prop="placeYard">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['place_yard']" :value="scope.row.placeYard"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否显示" prop="isShow" width="70">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isShow"/>
            </template>
          </el-table-column>
          <el-table-column label="医保科室名称" min-width="200" prop="medicalInsurance"></el-table-column>
          <el-table-column label="排序" min-width="80" prop="orderNum"></el-table-column>
          <el-table-column :align="'center'" label="状态" min-width="60" prop="status">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['sys_normal_disable']" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="创建时间" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作"
                           min-width="120px">
            <template #default="scope">
              <el-tooltip class="item" content="修改"
                          effect="dark"
                          placement="left">
                <el-button v-hasPerm="['system:dept:edit']" circle type="success" @click="handleUpdate(scope.row)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" content="新增"
                          effect="dark"
                          placement="top">
                <el-button v-hasPerm="['system:dept:edit']" circle type="primary" @click="handleAdd(scope.row)">
                  <template #icon>
                    <i-ep-plus/>
                  </template>
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" content="删除"
                          effect="dark"
                          placement="top">
                <el-button v-if="scope.row.parentId != 0" v-hasPerm="['system:dept:remove']" circle type="danger"
                           @click="handleDelete(scope.row)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改科室对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="700px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="40">
          <el-col v-if="form.parentId !== '0'" :span="24">
            <el-form-item label="上级科室" prop="parentId">
              <base-dept-tree :org-id="form.orgId" :value="form.parentId" style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="科室名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入科室名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室代码" prop="deptCode">
              <el-input v-model="form.deptCode" placeholder="请输入科室代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="临床标识" prop="clinicalSign">
              <el-select v-model="form.clinicalSign" placeholder="请选择临床标识" style="width: 100%;">
                <el-option v-for="dict in dictDataMap['clinical_sign']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室属性" prop="deptAttribute">
              <el-select v-model="form.deptAttribute" placeholder="请选择科室属性" style="width: 100%;">
                <el-option v-for="dict in dictDataMap['dept_attribute']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门诊住院" prop="clinicOrVisit">
              <el-select v-model="form.clinicOrVisit" placeholder="请选择门诊住院" style="width: 100%;">
                <el-option v-for="dict in dictDataMap['clinic_or_visit']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内外科标识" prop="internalOrSurgery">
              <el-select v-model="form.internalOrSurgery" placeholder="请选择内外科标识"
                         style="width: 100%;">
                <el-option v-for="dict in dictDataMap['internal_or_surgery']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在院区" prop="placeYard">
              <el-select v-model="form.placeYard" placeholder="请选择所在院区" style="width: 100%;">
                <el-option v-for="dict in dictDataMap['place_yard']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医保科室名称" prop="medicalInsurance">
              <el-input v-model="form.medicalInsurance" placeholder="请输入医保科室名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" maxlength="20" placeholder="请输入负责人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- prop="phone" -->
            <el-form-item label="联系电话">
              <el-input v-model="form.phone" maxlength="11" placeholder="请输入联系电话" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" maxlength="50" placeholder="请输入邮箱"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dictDataMap['sys_normal_disable']" :key="dict.dictValue"
                          :value="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示">
              <el-radio-group v-model="form.isShow">
                <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                          :value="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" controls-position="right"
                               style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  addDept,
  delDept,
  getDept,
  listDept,
  listDeptExcludeChild,
  refreshCacheDept,
  updateDept
} from "@/api/system/dept";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user"
import {email, telphone} from "@/utils/myRules"

const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
const {proxy} = getCurrentInstance() as any;
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const dictDataMap = ref(dictStore.isTypeGetData('sys_normal_disable', 'clinical_sign', 'dept_attribute',
  'clinic_or_visit', 'internal_or_surgery', 'place_yard', 'sys_yes_no'))
// 显示搜索条件
const showSearch = ref(true)
// 表格树数据
const deptList = ref([])
// 科室树选项
const deptOptions = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 是否展开，默认全部展开
const isExpandAll = ref(true)
// 重新渲染表格状态
const refreshTable = ref(true)
const formRef = ref()
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<Dept>({
  deptName: "",
  status: '',
  deptId: "",
  deptCode: ""
})
// 表单参数
const form = ref<Dept>({
  deptId: "",
  deptName: "",
  deptCode: "",
  isShow: "Y"
})
// 表单校验
const rules = ref({
  parentId: [
    {required: true, message: "上级科室不能为空", trigger: "blur"}
  ],
  deptName: [
    {required: true, message: "科室名称不能为空", trigger: "blur"}
  ],
  deptCode: [
    {required: true, message: "科室代码不能为空", trigger: "blur"}
  ],
  orderNum: [
    {required: true, message: "排序不能为空", trigger: "blur"}
  ],
  email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"]
    }
  ],
  phone: [
    {
      validator: telphone,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ]
})

watch(() => form.value.deptCode, (newValue, _oldValue) => {
  form.value.deptCode = newValue.replace(/[\u4e00-\u9fa5/\s+/]|[^a-zA-Z0-9\u4E00-\u9FA5]/g, "")
}, {deep: true})

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  getList()
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id
  getList()
}

/** 查询科室列表 */
function getList() {
  listDept(queryParams.value).then(response => {
    deptList.value = proxy.$handleTree(response.data, "deptId", "deptName");
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    deptId: "",
    parentId: "0",
    deptName: "",
    orderNum: 0,
    leader: "",
    phone: "",
    email: "",
    deptCode: "",
    clinicalSign: '0',
    deptAttribute: '0',
    clinicOrVisit: '0',
    internalOrSurgery: '0',
    placeYard: '1',
    medicalInsurance: "",
    status: "0",
    orgId: queryParams.value.orgId,
    isShow: "Y"
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  if (!userInfo.orgId && !form.value.orgId) {
    return ElMessage.error("请先选择所属机构后再新增")
  }
  if (row.deptId != undefined) {
    form.value.parentId = row.deptId;
  } else {
    form.value.parentId = "0"
  }
  open.value = true;
  title.value = "添加科室";
  listDept(queryParams.value).then(response => {
    deptOptions.value = proxy.$handleTree(response.data, "deptId", "deptName");

  });
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getDept(row.deptId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改科室";
    listDeptExcludeChild(row.deptId).then(response => {
      deptOptions.value = proxy.$handleTree(response.data, "deptId", "deptName");
      if (deptOptions.value.length == 0) {
        const noResultsOptions: any = {
          deptId: form.value.parentId,
          deptName: form.value.parentName,
          children: []
        };
        // @ts-ignore
        deptOptions.value.push(noResultsOptions);
      }
    });
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (userInfo.orgId) {
      form.value.orgId = userInfo.orgId
      form.value.orgName = userInfo.orgName
    }
    if (valid) {
      if (form.value.deptId != '') {
        updateDept(form.value).then(_response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then(_response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDept(row.deptId).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  });
}

function refreshCacheDeptFun() {
  refreshCacheDept().then((res: any) => {
    ElMessage.success(res.msg);
  })
}
</script>


<script lang="ts">
export default {
  name: "Dept"
};
</script>
